package dcdroplet;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
// Import Java JDK Classes
import java.util.Date;

/**
* @author dca
*/
public class XMLFileAppenderProperties extends AppenderProperties {
	@Override
	public void log(String tag, String msg, String msgFmt, String className, long timeStamp) {
		try {
			// Start a new file.
			if(0 == this.getFile().length()) {
				RandomAccessFile out = new RandomAccessFile(this.getFile(), "rw");
				out.writeBytes("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>"); out.writeBytes(NL);
				out.writeBytes("<" + this.getAppenderName() + ">");                out.writeBytes(NL);
				out.writeBytes("</" + this.getAppenderName() + ">");               out.writeBytes(NL);
				out.close();
			} // END if

			// Continue the file.
			RandomAccessFile out = new RandomAccessFile(this.getFile(), "rw");
			out.seek(out.length() - (long)("</" + this.getAppenderName() + ">" + NL).length());

			out.writeBytes("   <record");
			out.writeBytes(" timestamp=" + String.valueOf(timeStamp).replaceAll("(^|$)", "'"));
			out.writeBytes(" date=" + DATE.format(new Date(timeStamp)).replaceAll("(^|$)", "'"));
			out.writeBytes(" time=" + TIME.format(new Date(timeStamp)).replaceAll("(^|$)", "'"));
			out.writeBytes(">");                                 out.writeBytes(NL);

			out.writeBytes("      " +
				msgFmt.replace("${appender_name}", this.getAppenderName())
				      .replace("${class_name}", className)
				      .replace("${tag_name}",   tag)
				      .replace("${date}",       DATE.format(new Date(timeStamp)))
				      .replace("${time}",       TIME.format(new Date(timeStamp)))
				      .replace("${message}",    msg)
			);                                                   out.writeBytes(NL);
			out.writeBytes("   </record>");                      out.writeBytes(NL);
			out.writeBytes("</" + this.getAppenderName() + ">"); out.writeBytes(NL);
			out.close();
		} catch(FileNotFoundException fileExc) {
			System.err.printf("File not found: %s, for appender: %s%n", this.getFileDefinition(), this.getAppenderName());
		} catch(IOException ioExc) {
			System.err.printf("File write exception: %s, for appender: %s%n" + this.getFileDefinition(), this.getAppenderName());
		} // END try/catch
	} // END log
} // END class XMLFileAppenderProperties
